package com.cyc.quick.handler;

import com.cyc.quick.exception.ProjectException;
import com.cyc.quick.util.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @author chenyunchang
 * @title
 * @date 2020/5/9 15:12
 * @Description:
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * @author chenyunchang
     * @date 2020-05-12 20:08:02
     * @description 统一异常处理
     */
    @ExceptionHandler(value = Exception.class)
    public ApiResult jsonErrorHandler(Exception e) throws Exception {
        ApiResult result = new ApiResult();
        if (e instanceof HttpRequestMethodNotSupportedException) {
            logger.error(e.getMessage());
            return ApiResult.error("404", "请求方式错误");
        } else if (e instanceof MissingServletRequestParameterException) {
            logger.error(e.getMessage());
            return ApiResult.error("404", "传参有误");
        } else if (e instanceof ProjectException) {
            logger.error(e.getMessage());
            result.setCode(((ProjectException) e).getStatus());
            result.setMessage((e.getMessage()));
        } else {
            logger.error(e.getMessage(), e);
            result.setCode("500");
            result.setMessage("系统异常, 请稍后再试");
        }
        return result;
    }

}
